import unittest, os, sys
import greenlantern
from greenlantern import Mask
from greenlantern.filters import FilterFactory
from greenlantern.exceptions import *


def suite():
    lantern_suite = unittest.TestLoader().loadTestsFromTestCase(GreenLanternTest)
    filter_suite = unittest.TestLoader().loadTestsFromTestCase(FilterFactoryTest)
    suite = unittest.TestSuite([lantern_suite, filter_suite])
    return suite


class GreenLanternTest(unittest.TestCase):

    # TODO: Switch this to connect to a locally running web server that the unit tests control
    test_url = "http://www.google.com"
    
    resources_path = os.path.dirname(os.path.abspath(__file__)) + "/resources/"
    
    def setUp(self):
        pass
    
    def tearDown(self):
        pass

    def testLoadTemplateSuccess(self):
        mask = Mask()
        result = mask._loadTemplate(self.resources_path + "simple.template.lantern")
        self.assertEquals(type(result).__name__, "str")
        self.assertTrue(len(result) > 0)
    
    def testExtract(self):
        mask = Mask()
        content = mask._loadTemplate(self.resources_path + 'simple.content.html')
        result = mask.extract(self.resources_path + "simple.template.lantern", content)
        self.assertTrue((type(result).__name__ == "dict"), "It's not a dictionary object, fuck! It's actually a %s" % type(result).__name__)
        self.assertTrue((len(result) > 0), "It's empty. FML!")

    def testCompile(self):
        mask = Mask()
        content = mask._loadTemplate(self.resources_path + "simple.template.lantern")
        regex, variables, filters = mask._compileTemplate(content)
        # TODO: Check regex
        # TODO: Check variables
        # TODO: Check filters

    def testExtractVariables(self):
        pass
    
    def testMapVariables(self):
        mask = Mask()
        
        mask.registerFilter(TestFilters, 'trimText')
        
        variables = { 'var1': '   test' }
        filters = { 'var1': 'trimText' }
        cleaned = mask._mapVariables(variables, filters)

    def testEscapeTemplate(self):
        mask = Mask()
        starting = "abcd []{}()*+?.\\|^$-,&# {{ token }} more text"
        expected = "abcd \\[\\]\\{\\}\\(\\)\\*\\+\\?\\.\\\\\|\\^\\$\\-\\,\\&\\# {{ token }} more text"
        result = mask._escapeTemplate(starting)
        self.assertEquals(result, expected)
        
        
class TestFilters():
    
    def trimText(self, text):
        return text.strip()
        
        
class FilterFactoryTest(unittest.TestCase):
    
    def testRegisterFilter(self):
        f = FilterFactory()
        f.registerFilter(greenlantern.filters, ['stripHTML'])
        func = f.getFilter('stripHTML')
        self.assertEquals(greenlantern.filters.stripHTML, func)
        self.assertEquals('test', func('test', 'test') )
        self.assertRaises(FilterNotFoundException, f.getFilter('junk'))
        
        
if __name__ == "__main__":
    unittest.TextTestRunner(verbosity=2).run(suite())
